<template>
  <div class="app-container">
    <el-row>
      <el-col :span="24">
        <div class="h_top">
          <div class="bread_title">
            <span>提交采购申请</span>
          </div>
          <div class="save_button">
            <div v-if="reviewS" class="buttonBox">
              <el-button type="success" icon="el-icon-check" size="mini" @click="reviewSuccess">请求审核</el-button>
            </div>
            <div v-if="reviewB" class="buttonBox">
              <el-button type="danger" icon="el-icon-close" size="mini" @click="reviewBack">退回审核</el-button>
            </div>
            <div v-if="reviewEngineerS" class="buttonBox">
              <el-button type="success" icon="el-icon-check" size="mini" @click="reviewEngineerSuccess">通过（工程师）</el-button>
            </div>
            <div v-if="reviewEngineerB" class="buttonBox">
              <el-button type="danger" icon="el-icon-close" size="mini" @click="reviewEngineerBack">退回（工程师）</el-button>
            </div>
            <div v-if="reviewKzS" class="buttonBox">
              <el-button type="success" icon="el-icon-check" size="mini" @click="reviewKzSuccess">通过（科长）</el-button>
            </div>
            <div v-if="reviewKzB" class="buttonBox">
              <el-button type="danger" icon="el-icon-close" size="mini" @click="reviewKzBack">退回（科长）</el-button>
            </div>
            <div class="buttonBox">
              <el-button type="primary" icon="el-icon-back" size="mini" @click="goBack">返回</el-button>
            </div>
            <div class="buttonBox">
              <el-button type="primary" icon="el-icon-document-checked" size="mini" @click="save">保存</el-button>
            </div>
            <div class="buttonBox">
              <el-button type="primary" icon="el-icon-document-remove" size="mini" @click="confirmDel">删除</el-button>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
    <div>
      <el-row>
        <el-col :span="24">
          <el-form ref="form" :model="data" :inline="true" :rules="formRules">
            <el-input v-model="data.id" type="hidden" />
            <el-row :gutter="10">
              <el-col :xl="3" :lg="4" :md="5" :sm="6">
                <el-form-item prop="coding">
                  <div>编号</div>
                  <el-input v-model="data.coding" size="mini" :disabled="alreadyReview" />
                </el-form-item>
              </el-col>
              <el-col :xl="3" :lg="4" :md="5" :sm="6">
                <el-form-item prop="name">
                  <div>名称</div>
                  <el-input v-model="data.name" size="mini" :disabled="alreadyReview" />
                </el-form-item>
              </el-col>
              <el-col :xl="4" :lg="4" :md="5" :sm="6" hidden>
                <el-form-item prop="factory_id">
                  <div>所属工厂</div>
                  <v-select v-model="data.factory_id" action="factoryList" :disabled="alreadyReview" />
                </el-form-item>
              </el-col>
              <el-col :xl="3" :lg="4" :md="5" :sm="6">
                <el-form-item prop="admin_id">
                  <div>申请人员</div>
                  <v-select v-model="data.admin_id" disabled />
                </el-form-item>
              </el-col>
              <el-col :xl="3" :lg="4" :md="5" :sm="6">
                <el-form-item prop="status">
                  <div>状态</div>
                  <el-select v-model="data.status" size="mini" :disabled="alreadyReview">
                    <el-option v-for="(item, index) in applyStatus" :key="index" :value="index" :label="item" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xl="4" :lg="4" :md="5" :sm="6">
                <el-form-item prop="review_id">
                  <div>审核岗位</div>
                  <v-select v-model="data.review_id" action="jobList" :query="{type:'gcs'}" :disabled="reviewId" />
                </el-form-item>
              </el-col>
              <el-col :xl="3" :lg="4" :md="5" :sm="6" hidden>
                <el-form-item prop="kind">
                  <div>采购物品</div>
                  <el-select v-model="data.kinds" size="mini" :disabled="true">
                    <el-option v-for="(item, index) in applyKind" :key="index" :value="index" :label="item" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xl="3" :lg="4" :md="5" :sm="6">
                <el-form-item prop="sort">
                  <div>排序</div>
                  <el-input v-model="data.sort" size="mini" />
                </el-form-item>
              </el-col>
              <div v-if="data.verify_admin">
                <el-col :xl="3" :lg="4" :md="5" :sm="6">
                  <el-form-item>
                    <div>验证人员</div>
                    <el-input v-model="data.verify_admin.name" :disabled="true" size="mini" />
                  </el-form-item>
                </el-col>
                <el-col :xl="3" :lg="4" :md="5" :sm="6">
                  <el-form-item>
                    <div>验证时间</div>
                    <el-input v-model="data.verify_date" :disabled="true" size="mini" />
                  </el-form-item>
                </el-col>
              </div>
            </el-row>
          </el-form>
          <el-tabs>
            <el-tab-pane label="详细">
              <el-table :data="parts.data">
                <el-table-column label="备品备件-型号" min-width="12%">
                  <template slot-scope="scope">
                    <div v-if="scope.row.parts">
                      {{ scope.row.parts.name }}-{{ scope.row.parts.spec }}
                    </div>
                    <div v-else>该备件已经被删除</div>
                  </template>
                </el-table-column>
                <el-table-column label="种类" prop="gz" min-width="8%" :formatter="statusFormat" />
                <el-table-column label="适用于" prop="eq.name" min-width="12%" />
                <el-table-column label="参考编号" prop="parts.coding" min-width="9%" />
                <el-table-column label="注意" prop="notice" min-width="13%">
                  <template slot-scope="scope">
                    <span v-if="scope.row.isSet">
                      <el-input v-model="editNotice" size="mini" placeholder="请输入内容" />
                    </span>
                    <span v-else>
                      {{ scope.row.notice }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column label="数量" prop="number" min-width="8%">
                  <template slot-scope="scope">
                    <span v-if="scope.row.isSet">
                      <el-input v-model="editNumber" size="mini" placeholder="请输入内容" />
                    </span>
                    <span v-else>
                      {{ scope.row.number }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column label="当前数量" prop="parts.number" min-width="9%" />
                <el-table-column label="单价 (¥)" prop="price" min-width="8%">
                  <template slot-scope="scope">
                    <span v-if="scope.row.isSet">
                      <el-input v-model="editPrice" size="mini" placeholder="请输入内容" />
                    </span>
                    <span v-else>
                      {{ scope.row.price }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column label="需要日期" prop="datetime" min-width="13%">
                  <template slot-scope="scope">
                    <span v-if="scope.row.isSet">
                      <el-date-picker v-model="editDatetime" type="date" value-format="yyyy-MM-dd" size="mini" />
                    </span>
                    <span v-else>
                      {{ scope.row.datetime }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column label="操作" min-width="8%">
                  <template v-slot="scope">
                    <div v-if="canAppend">
                      <span class="el-tag el-tag--info el-tag--mini cur" @click="editOrCancel(scope.row,scope.$index,true)">
                        {{ scope.row.isSet?'保存':"修改" }}
                      </span>
                      <span v-if="!scope.row.isSet" class="el-tag el-tag--danger el-tag--mini cur" @click="remove(scope.row.id)">
                        删除
                      </span>
                      <span v-else class="el-tag el-tag--mini cur" @click="editOrCancel(scope.row,scope.$index,false)">
                        取消
                      </span>
                    </div>
                    <div v-else>
                      <span>-</span>
                    </div>
                  </template>
                </el-table-column>
                <div v-if="canAppend" slot="append">
                  <el-form ref="append_form" :model="order" :inline="true" class="hf_form append_other_admin" :rules="appendRules">
                    <el-row :gutter="10">
                      <el-col :span="3">
                        <el-form-item prop="parts_id">
                          <v-select-s v-model="order.parts_id" action="partsList" :query="{'add_field': 'spec'}" />
                        </el-form-item>
                      </el-col>
                      <el-col :span="2">
                        <el-form-item prop="gz">
                          <el-select v-model="order.gz" size="mini">
                            <el-option v-for="(item, index) in applyCategory" :key="index" :value="index" :label="item" />
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="3">
                        <el-form-item prop="equipment_id">
                          <v-select-s v-model="order.equipment_id" action="eqList" :query="{'gz':order.gz, 'add_field': 'spec'}" />
                        </el-form-item>
                      </el-col>
                      <el-col :span="2">
                        <el-form-item>
                          <el-input v-model="order.coding" :disabled="true" size="mini" />
                        </el-form-item>
                      </el-col>
                      <el-col :span="3">
                        <el-form-item prop="notice">
                          <el-input v-model="order.notice" size="mini" />
                        </el-form-item>
                      </el-col>
                      <el-col :span="2">
                        <el-form-item prop="number">
                          <el-input v-model="order.number" size="mini" />
                        </el-form-item>
                      </el-col>
                      <el-col :span="2">
                        <el-form-item>
                          <el-input v-model="order.coding" :disabled="true" size="mini" />
                        </el-form-item>
                      </el-col>
                      <el-col :span="2">
                        <el-form-item prop="price">
                          <el-input v-model="order.price" size="mini" />
                        </el-form-item>
                      </el-col>
                      <el-col :span="3">
                        <el-form-item prop="datetime">
                          <el-date-picker v-model="order.datetime" type="date" value-format="yyyy-MM-dd" size="mini" />
                        </el-form-item>
                      </el-col>
                      <el-col :span="2">
                        <el-form-item>
                          <el-button icon="el-icon-upload2" size="mini" @click="append" />
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </el-form>
                </div>
              </el-table>
            </el-tab-pane>
            <el-tab-pane label="审核工程师">
              <el-table :data="admins">
                <el-table-column label="工程师" prop="admin.name" min-width="92%" />
                <el-table-column label="操作" min-width="8%">
                  <template v-slot="scope">
                    <div v-if="canAppend">
                      <span class="el-tag el-tag--danger el-tag--mini cur" @click="removeAdmin(scope.row.id)">
                        删除
                      </span>
                    </div>
                    <div v-else>
                      <span>-</span>
                    </div>
                  </template>
                </el-table-column>
                <div v-if="canAppend" slot="append">
                  <el-form ref="admin_form" :model="admin" :inline="true" class="hf_form append_other_admin" :rules="adminRules">
                    <el-row :gutter="10">
                      <el-col :span="22">
                        <el-form-item prop="admin_id">
                          <v-select v-model="admin.admin_id" :query="{'category_id': data.review_id}" multiple />
                        </el-form-item>
                      </el-col>
                      <el-col :span="2">
                        <el-form-item>
                          <el-button icon="el-icon-upload2" size="mini" @click="appendAdmin" />
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </el-form>
                </div>
              </el-table>
            </el-tab-pane>
            <el-tab-pane label="描述">
              <el-row :gutter="10">
                <el-col :xl="4" :lg="4" :md="5" :sm="6">
                  <div>
                    <span>创建时间日期</span>
                    <el-input v-model="data.create_time" placeholder="创建时间日期" class="mtb10" size="mini" :disabled="true" />
                  </div>
                  <div>
                    <span>创建人</span>
                    <el-input v-model="data.cr_admin.name" placeholder="创建人" class="mtb10" size="mini" :disabled="true" />
                  </div>
                  <div v-if="data.update_time">
                    <div>
                      <span>最近更新</span>
                      <el-input v-model="data.update_time" placeholder="最近更新" class="mtb10" size="mini" :disabled="true" />
                    </div>
                    <div>
                      <span>更新者</span>
                      <el-input v-model="data.up_admin.name" placeholder="更新者" class="mtb10" size="mini" :disabled="true" />
                    </div>
                  </div>
                </el-col>
                <el-col :span="20">
                  <Tinymce id="content" v-model="data.content" />
                </el-col>
              </el-row>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import API from '@/api/stock/apply'
import { mapGetters } from 'vuex'
import { applyStatus, applyKind, applyCategory } from '@/utils/options'
import VSelect from '@/components/select'
import VSelectS from '@/components/select-search'
import Tinymce from '@/components/Tinymce/index'
export default {
  inject: ['backUrl', 'delOne', 'update', 'appendParts', 'removeParts', 'reload', 'backUrl', 'getGroupTypeFormat', 'goUrl'],
  components: {
    VSelect,
    VSelectS,
    Tinymce
  },
  data() {
    return {
      data: {
        'cr_admin': {
          'name': ''
        },
        'verify_admin': {
          'name': ''
        },
        'kinds': 0
      },
      parts: {
        sel: null,
        data: []
      },
      admin: {},
      admins: [],
      editId: '',
      editNumber: '',
      editPrice: '',
      editDatetime: '',
      editNotice: '',
      reviewS: false,
      reviewB: false,
      reviewEngineerS: false,
      reviewEngineerB: false,
      reviewKzS: false,
      reviewKzB: false,
      alreadyReview: false,
      reviewId: true,
      canAppend: false,
      order: {},
      applyStatus,
      applyKind,
      applyCategory,
      formRules: {
        coding: [
          {
            required: true,
            message: '请输入编号',
            trigger: 'blur'
          }
        ],
        name: [
          {
            required: true,
            message: '请输入申请单名称',
            trigger: 'blur'
          }
        ],
        factory_id: [
          {
            required: true,
            message: '请选择工厂',
            trigger: 'change'
          }
        ],
        admin_id: [
          {
            required: true,
            message: '请选择申请人员',
            trigger: 'change'
          }
        ],
        status: [
          {
            required: true,
            message: '请选择状态',
            trigger: 'change'
          }
        ],
        review_id: [
          {
            required: true,
            message: '请选择审核工程师',
            trigger: 'change'
          }
        ],
        sort: [
          {
            required: true,
            message: '请输入排序',
            trigger: 'blur'
          }
        ]
      },
      appendRules: {
        parts_id: [
          {
            required: true,
            message: '请选择采购物品',
            trigger: 'change'
          }
        ],
        provider_id: [
          {
            required: true,
            message: '请选择供应商',
            trigger: 'change'
          }
        ],
        number: [
          {
            required: true,
            message: '请填写数量',
            trigger: 'blur'
          }
        ],
        price: [
          {
            required: true,
            message: '请填写价格',
            trigger: 'blur'
          }
        ],
        datetime: [
          {
            required: true,
            message: '请填写日期',
            trigger: 'blur'
          }
        ]
      },
      adminRules: {
        admin_id: [
          {
            required: true,
            message: '请选择审核人员',
            trigger: 'change'
          }
        ]
      },
      atFirst: false
    }
  },
  computed: {
    ...mapGetters([
      'roles',
      'userId'
    ])
  },
  created() {
    const id = this.$route.params.id
    API.getOne(id).then(response => {
      console.log(response.data)
      if (response.data.error_code === 51404) {
        this.$alert('您请求的采购申请单不存在', '错误', {
          confirmButtonText: '确定',
          callback: () => {
            this.backUrl()
          }
        })
      }
      this.data = response.data
      this.parts.data = response.data.part
      this.data.kinds = response.data.kind - 1
      this.admins = response.data.admins_list
      this.parts.data.forEach(i => {
        this.$set(i, 'isSet', false)
      })
      if (!response.data.review_id) {
        this.reviewId = false
      }
      const thisRole = this.roles[0]
      if (response.data.status === 1 || response.data.status === 3) {
        this.alreadyReview = true
      }
      if (response.data.admin_id === this.userId) {
        if (response.data.status === 0) {
          this.reviewS = true
        }
        if (response.data.status === 1) {
          this.reviewB = true
        }
      }
      if (this.roles.includes(response.data.review_id) || this.roles.includes(16)) {
        if (response.data.status === 1 || response.data.status === 4) {
          this.reviewEngineerS = true
        }
        if (response.data.status === 1 || response.data.status === 2 || response.data.status === 4) {
          this.reviewEngineerB = true
        }
      }
      if (response.data.status === 0 || response.data.status === 2 || response.data.status === 4) {
        this.canAppend = true
      }
      const kz = [124, 125, 16]
      if (kz.includes(thisRole)) {
        if (response.data.status === 2 || response.data.status === 5) {
          this.reviewKzS = true
        }
        if (response.data.status === 2 || response.data.status === 3 || response.data.status === 5) {
          this.reviewKzB = true
        }
      }
      if (this.status === 0) {

      }
    })
  },
  methods: {
    confirmDel() {
      const id = this.data.id
      this.delOne(API, id, true)
    },
    save() {
      const thisData = this.data
      const thisForm = this.$refs.form
      this.update(API, thisData, thisForm)
    },
    append() {
      const thisForm = this.$refs.append_form
      const parts_data = {
        'parts_id': this.order.parts_id,
        'gz': this.order.gz,
        'equipment_id': this.order.equipment_id,
        'notice': this.order.notice,
        'number': this.order.number,
        'price': this.order.price,
        'datetime': this.order.datetime,
        'applyFor_id': this.$route.params.id
      }
      const errorCode = 51004
      const errorMessage = '该备件已存在'
      this.appendParts(API, thisForm, parts_data, errorCode, errorMessage)
    },
    appendAdmin() {
      const self = this
      API.appendAdmin({ apply_id: self.$route.params.id, admins: this.admin.admin_id }).then(res => {
        console.log(res.data.message)
        if (res.data.error_code === 1) {
          self.$message({
            message: '恭喜你，增加成功',
            type: 'success'
          })
          API.getOne(self.$route.params.id).then(() => {
            self.reload()
          })
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    removeAdmin(id) {
      const self = this
      API.removeAdmin({ admin_id: id }).then(res => {
        if (res.data.error_code === 1) {
          self.$message({
            message: '恭喜你，删除成功',
            type: 'success'
          })
          API.getOne(self.$route.params.id).then(() => {
            self.reload()
          })
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    remove(id) {
      const parts_data = {
        'id': id
      }
      this.removeParts(API, id, parts_data)
    },
    editOrCancel(row, index, cg) {
      // 点击修改 判断是否已经保存所有操作
      for (const i of this.parts.data) {
        if (i.isSet && i.id !== row.id) {
          this.$message.warning('请先保存当前编辑项')
          return false
        }
      }
      // 是否是取消操作
      if (!cg) {
        if (!this.parts.sel.id) {
          this.parts.data.splice(index, 1)
        }
        return this.$set(this.parts.data[index], 'isSet', false)
      }
      // 提交数据
      const _this = this
      if (row.isSet) {
        // 项目是模拟请求操作  自己修改下
        (function() {
          const edit_parts_data = {
            'notice': _this.editNotice,
            'number': _this.editNumber,
            'price': _this.editPrice,
            'datetime': _this.editDatetime,
            'applyFor_id': _this.editId
          }
          API.edit(edit_parts_data).then(response => {
            if (response.data.error_code === 1) {
              _this.$message({
                message: '恭喜你，更新成功',
                type: 'success'
              })
              API.getOne(_this.$route.params.id).then(() => {
                _this.reload()
              })
            } else {
              this.$message.error(response.data.message)
            }
          })
        })()
      } else {
        this.parts.sel = JSON.parse(JSON.stringify(row))
        this.$set(this.parts.data[index], 'isSet', true)
        this.editNumber = this.parts.data[index].number
        this.editPrice = this.parts.data[index].price
        this.editDatetime = this.parts.data[index].datetime
        this.editNotice = this.parts.data[index].notice
        this.editId = this.parts.data[index].id
      }
    },
    reviewSuccess() {
      const reviewData = {
        'status': 1,
        'content': this.data.content,
        'id': this.data.id
      }
      if (!this.data.review_id) {
        this.$message.error('请先选择审核岗位')
        return
      } else {
        reviewData.review_id = this.data.review_id
      }
      API.review(reviewData).then(response => {
        if (response.data.error_code === 1) {
          this.$message.success('请求！')
          this.backUrl()
        } else {
          this.$message.error(response.data.message)
        }
      })
    },
    reviewBack() {
      const reviewData = {
        'status': 0,
        'content': this.data.content,
        'id': this.data.id
      }
      API.review(reviewData).then(response => {
        if (response.data.error_code === 1) {
          this.$message.success('退回！')
          this.backUrl()
        } else {
          this.$message.error(response.data.message)
        }
      })
    },
    reviewEngineerSuccess() {
      const reviewData = {
        'status': 2,
        'content': this.data.content,
        'id': this.data.id
      }
      API.review(reviewData).then(response => {
        if (response.data.error_code === 1) {
          this.$message.success('审批！')
          this.backUrl()
        } else {
          this.$message.error(response.data.message)
        }
      })
    },
    reviewEngineerBack() {
      if (!this.data.content) {
        this.$message.error('请填写退回原因（在描述中填写）')
        return false
      }
      const reviewData = {
        'status': 4,
        'content': this.data.content,
        'id': this.data.id
      }
      API.review(reviewData).then(response => {
        if (response.data.error_code === 1) {
          this.$message.success('退回！')
          this.backUrl()
        } else {
          this.$message.error(response.data.message)
        }
      })
    },
    reviewKzSuccess() {
      const reviewData = {
        'status': 3,
        'content': this.data.content,
        'id': this.data.id
      }
      API.review(reviewData).then(response => {
        if (response.data.error_code === 1) {
          this.$message.success('审批！')
          this.backUrl()
        } else {
          this.$message.error(response.data.message)
        }
      })
    },
    reviewKzBack() {
      if (!this.data.content) {
        this.$message.error('请填写退回原因（在描述中填写）')
        return false
      }
      const reviewData = {
        'status': 5,
        'content': this.data.content,
        'id': this.data.id
      }
      API.review(reviewData).then(response => {
        if (response.data.error_code === 1) {
          this.$message.success('退回！')
          this.backUrl()
        } else {
          this.$message.error(response.data.message)
        }
      })
    },
    statusFormat(row) {
      return this.getGroupTypeFormat(row)
    },
    goBack() {
      this.goUrl('/stock/apply')
    }
  }
}
</script>
